<template>
  <div class="collections-page">
    <div class="big-panel-tit">我的收藏</div>
    <div class="fav-tab">
      <div class="tabs">
        <a :class="{ 'active': params.type === '','has-cir':(cirObj.game+cirObj.article+cirObj.work+cirObj.img)>0}" @click="chooseFolderType('')">全部收藏<i
            class="num">{{ nums.explorerArticleCount + nums.explorerImagesCount }}</i></a>
        <a :class="{ 'active': params.type === 1 ,'has-cir':(cirObj.game+cirObj.article+cirObj.work)>0}" @click="chooseFolderType(1)">图片集收藏夹<i
            class="num">{{ nums.explorerImagesCount }}</i></a>
        <a :class="{ 'active': params.type === 0 ,'has-cir':(cirObj.img>0)}" @click="chooseFolderType(0)">单图收藏夹<i
            class="num">{{ nums.explorerArticleCount }}</i></a>
        <!-- <a :class="{'active':params.type===2}" @click="chooseFolderType(2)">视频收藏夹<i class="num">{{statistics.sortVideoCount}}</i></a> -->
      </div>
      <div class="seach-bx">
        <form @submit.prevent="() => { return false; }">
          <input type="text" v-model="params.title" @keypress.enter="handleSearch" placeholder="搜索"><i
            v-if="params.title" @click="params.title = ''" class="clear-by-search"></i>
        </form>
      </div>
    </div>
    <ul class="fav-datas">
      <li class="fav-d-item create-btn" v-if="(params.type || params.type === 0) && myself">
        <a @click="handleShowCreate">
          <span class="plus-icon">+</span>
          <span class="text">创建{{ folderTypeEnum[params.type] }}</span>
        </a>
      </li>
      <li class="fav-d-item" :class="{'no-data':!f.id}" v-for="(f, i) in list" :key="i" @click="toFoldInfo(f)">
        <template v-if="f.id">
          <div class="img-flex-box">
            <div class="lt-img">
              <img loading="lazy" v-if="f.collectList && f.collectList.length > 0" @load="(e) => { onLoaded(e, f.collectList[0], 408, true) }"
                v-lazy="getimgObj(f.collectList[0], 408, true)" alt="" />
            </div>
            <div class="rt-img">
              <div class="next-img">
                <img loading="lazy" v-if="f.collectList && f.collectList.length > 1" @load="(e) => { onLoaded(e, f.collectList[1], 204, true) }"
                  v-lazy="getimgObj(f.collectList[1], 204, true)" alt="" />
              </div>
              <div class="last-img">
                <img loading="lazy" v-if="f.collectList && f.collectList.length > 2" @load="(e) => { onLoaded(e, f.collectList[2], 204, true) }"
                  v-lazy="getimgObj(f.collectList[2], 204, true)" alt="" />
              </div>
            </div>
            <div class="ops">
              <a class="i-del" title="删除" @click.stop="id = f.id; showDelConfirm = true;"></a>
              <a class="i-edit" title="编辑" @click.stop="record = Object.assign({}, f); ftype = f.type; showCreate = true;"
                target="_blank"></a>
            </div>
          </div>
          <div class="bot-desc">
            <span class="file-name">{{ f.title }}</span>
            <span class="file-num">{{ f.num }} 收藏</span>
          </div>
          <div class="f-type-row">
            <span class="f-type" :class="['ftp_' + f.type]">{{ folderTypeEnum[f.type] }}</span>
          </div>
        </template>
      </li>
    </ul>
    <Empty text="没有找到符合条件的结果~" v-if="params.type === '' && list.length == 0 && !isloading" />
    <div class="no-more-text" v-if="!hasMore && !isloading && list.length > 0">没有更多了</div>

    <a-modal v-model="showCreate" destroyOnClose centered :footer="null" :closable="false">
      <CreateFolder ref="refCreateFolder" @close="onClose" :info="record" :foldertype="ftype" />
    </a-modal>

    <a-modal v-model="showDelConfirm" destroyOnClose centered :footer="null" :closable="false" width="366px">
      <div class="fav-component">
        <div class="fav-header">
          系统提示
        </div>
        <div class="folder-con" style="margin-top:30px;text-align:center;font-size:14px;">
          确定删除吗？删除后当前内容都会被删除且不可恢复。
        </div>
        <div class="btns m-widbtns">
          <a class="pro-default-btn" @click="handleConfirmDel">确认</a>
          <a class="pro-confirm-btn" @click="showDelConfirm = false">取消</a>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import Empty from '@/components/Empty'
import CreateFolder from '@/components/CreateFolder'
import api from '@/api/api'
export default {
  components: { CreateFolder, Empty },
  data() {
    return {
      cirObj:{
        img:0,
        article:0,
        game:0,
        work:0
      },
      scrollPosition: 0,
      nums: {
        article: 0,//文章分类
        articleAll: 0,//总文章数
        discover: 0,//发现分类
        draft: 0,//文章草稿数
        explorerArticleCount: 0,//图片集文件夹
        explorerImagesCount: 0,//图片文件夹数
        explorerTotalCount: 0,//文件夹总数
        fansCount: 0,//粉丝
        linggan: 0,//灵感分类
        material: 0,//材质分类
        praisedCount: 0,//点赞数
        subscribeCount: 0,//关注
        publishTotalCount: 0,
        sortVideoCount: 0,
        collectCount: 0
      },
      isloading: true,
      ftype: '',
      id: '',
      record: null,
      showDelConfirm: false,
      folderTypeEnum: {
        1: '图片集收藏夹',
        0: '单图收藏夹',
        2: '短视频收藏夹'
      },
      myself: true,
      showCreate: false,
      nextPageEnum: {
        '': '/',
        1: '/collection/games',
        0: '/collection/imgs',
        2: '/collection/videos'
      },
      params: {
        pageNum: 1,
        pageSize: 20,
        type: ''
      },
      scrollLoaded: false,
      hasMore: true,
      list: []
    }
  },
  destroyed() {
      window.removeEventListener('scroll', this.docScroll);
  },
  activated(){
      window.addEventListener('scroll', this.docScroll);
      let that=this;
      this.$nextTick(() => {
          window.scrollTo(0,that.scrollPosition)
      });
  },
  deactivated(){
      window.removeEventListener('scroll', this.docScroll);
  },
  methods: {
    docScroll(e){
      this.scrollPosition=e.currentTarget.scrollY;
      let that=this;
      let jHeight = document.documentElement.scrollHeight - document.documentElement.scrollTop - document.documentElement.clientHeight

      if (that.scrollLoaded == false) return

      if (jHeight <= 50 && that.hasMore) {
        that.scrollLoaded = false
        that.handleLoadingMore()
      }
    },
    onLoaded(e, item, w, isimg) {
      let domainUrl = this.$imgdomainurl;
      let el = e.target;
      let _vtime = null;
      if (item.updateTime) {
        _vtime = item.updateTime;
      } else if (item.createTime) {
        _vtime = item.createTime;
      } else if (item.create_time) {
        _vtime = item.create_time.replace('T', ' ');
      }
      _vtime = Math.abs(new Date(_vtime).getTime());
      let srcsets = [];

      if (isimg) {
        let _url = this.$imgdomainurl + (item.imageId ? item.imageId : (item.article ? 'article-' + item.article.id : '')) + '-' + _vtime;
        if (!item.imageId && !item.article)
          _url = item.content;
        else {
          srcsets.push(_url + '@1x' + w + '.webp 1x');
          srcsets.push(_url + '@2x' + w + '.webp 2x');
          srcsets.push(_url + '@3x' + w + '.webp 3x');

          el.srcset = srcsets.join(',')
        }
      } else {
        srcsets.push(domainUrl + item.id + '-' + _vtime + '@1x' + w + '.webp 1x');
        srcsets.push(domainUrl + item.id + '-' + _vtime + '@2x' + w + '.webp 2x');
        srcsets.push(domainUrl + item.id + '-' + _vtime + '@3x' + w + '.webp 3x');
        el.srcset = srcsets.join(',')
      }
    },
    getimgObj(item, w, isimg) {
      let _vtime = null;
      if (item.updateTime) {
        _vtime = item.updateTime;
      } else if (item.createTime) {
        _vtime = item.createTime;
      } else if (item.create_time) {
        _vtime = item.create_time.replace('T', ' ');
      }
      _vtime = Math.abs(new Date(_vtime).getTime());
      if (isimg) {
        if (!item) {
          return {
            src: require('@/assets/loading_error.png'),
            error: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png'),
            loading: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png')
          }
        } else {
          let _url = this.$imgdomainurl + (item.imageId ? item.imageId : (item.article ? 'article-' + item.article.id : '')) + '-' + _vtime + '@1x' + w + '.webp';
          if (!item.imageId && !item.article)
            _url = item.content;
          return {
            src: _url,
            error: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png'),
            loading: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png')
          }
        }
      } else {
        return {
          src: this.$imgdomainurl + item.id + '-' + _vtime + '@1x' + w + '.webp',
          error: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png'),
          loading: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png')
        }
      }
    },
    async queryStatistics() {
      let res = await api.getMemberArticleAndExplorerStatistics(localStorage.getItem('userId'));
      this.nums = res.data;
    },
    handleShowCreate() {
      this.ftype = this.params.type;
      this.record = {};
      this.showCreate = true;
      // this.$refs['refCreateFolder'].visible=true;
    },
    toFoldInfo(f) {
      if(!f.id)return;
      localStorage.setItem('FOL-BACK-P', this.$router.currentRoute.fullPath);
      this.$router.push({ path: this.nextPageEnum[f.type] + '/' + f.id })
      // let routeData = this.$router.resolve({ path: this.nextPageEnum[f.type] + '/' + f.id });

      // window.open(routeData.href, '_blank');
    },
    async handleConfirmDel() {
      let res = await api.removeSinglePicFav(this.id);
      this.showDelConfirm = false;
      if (res.code == 0) {
        this.list = [];
        this.hasMore = true;
        this.$amessage.success('删除成功')
        this.queryList();
      }
    },
    onClose(isRefresh) {
      this.showCreate = false;
      if (isRefresh) {
        this.list = [];
        this.scrollLoaded = false;
        this.hasMore = true;
        this.params.pageNum = 1;
        this.queryList();
      }
    },
    chooseFolderType(_ftype) {
      if(_ftype==1){
        this.cirObj.game=0;
        this.cirObj.article=0;
        this.cirObj.work=0;
        localStorage.removeItem('CIR-COLLECT-GAME')
        localStorage.removeItem('CIR-COLLECT-ARTICLE')
        localStorage.removeItem('CIR-COLLECT-WORK')
      }else if(_ftype===0){
        this.cirObj.img=0;
        localStorage.removeItem('CIR-COLLECT-IMG')
      }
      this.ftype = _ftype;
      // if(this.params.type===_ftype)return;
      this.params.type = _ftype;
      this.list = [];
      this.params.pageNum = 1;
      this.scrollLoaded = false;
      this.hasMore = true;
      window.history.pushState({}, 0, '/myCollection' + (_ftype || _ftype == 0 ? '?t=' + _ftype : ''));

      this.queryStatistics();
      this.queryList();
    },
    handleLoadingMore() {
      this.params.pageNum++;
      this.queryList()
    },
    handleSearch() {
      this.params.pageNum = 1;
      this.list = [];
      this.isloading = true;
      this.scrollLoaded = false;
      this.hasMore = true;
      this.queryList();
    },
    async queryList() {
      let res = {};
      let that = this;
      let _params = Object.assign({}, this.params);
      if (!_params.type && _params.type !== 0) {
        delete _params.type;
      }
      this.isloading = true;
      if(_params.pageNum==1){
        this.list=[{},{},{},{},{},{},{},{},{}]
      }
      res = await api.explorerList(_params);
      this.isloading = false;
      if(_params.pageNum==1){
        this.list=[];
      }
      if (res.data) {
        this.list = [...this.list, ...res.data];

        let totalPage = res.total % that.params.pageSize == 0 ? res.total / that.params.pageSize : parseInt(res.total / that.params.pageSize) + 1
        if (res.data && (res.data.length < that.params.pageSize || that.params.pageNum >= totalPage)) {
          that.hasMore = false
        } else {
          that.hasMore = true
        }
        that.scrollLoaded = true
      }
    }
  },
  mounted() {
    let token = localStorage.getItem('token')
    if (!token) {
      this.$parent.showLoginView = true;
      return;
    }
    if(localStorage.getItem('CIR-COLLECT-GAME')){
      this.cirObj.game=parseInt(localStorage.getItem('CIR-COLLECT-GAME'));
    }
    if(localStorage.getItem('CIR-COLLECT-ARTICLE')){
      this.cirObj.article=parseInt(localStorage.getItem('CIR-COLLECT-ARTICLE'));
    }
    if(localStorage.getItem('CIR-COLLECT-WORK')){
      this.cirObj.work=parseInt(localStorage.getItem('CIR-COLLECT-WORK'));
    }
    if(localStorage.getItem('CIR-COLLECT-IMG')){
      this.cirObj.img=parseInt(localStorage.getItem('CIR-COLLECT-IMG'));
    }
    if (this.$route.query.t || this.$route.query.t === 0) {
      this.params.type = parseInt(this.$route.query.t);
    }
    this.chooseFolderType(this.params.type);
    this.queryStatistics();
  }
}
</script>

<style lang="less">
.collections-page {
  display: inline-block;
  width: 100%;
  height: 100%;

  .big-panel-tit {
    font-size: 26px;
    font-weight: 500;
    line-height: 37px;
    margin-bottom: 27px;
  }

  .fav-tab {
    font-size: 18px;
    color: #969696;
    margin-bottom: 29px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .tabs {
      a {
        margin-right: 40px;
        display: inline-block;
        line-height: 25px;
        height: 25px;
        position: relative;
        transition:.2s all linear;
        i {
          font-style: normal;
          font-size: 16px;
          margin-left: 4px;
        }

        &.active {
          color: #fff;

          &:after {
            content: '';
            position: absolute;
            bottom: -5px;
            left: calc((100% - 24px) / 2);
            width: 24px;
            height: 2px;
            background: #11CCB1;
          }
        }
        &.has-cir{
          &:before{
            content:'';
            position: absolute;
            width:6px;height:6px;
            border-radius:3px;
            background:#11CCB1;
            right:-9px;
            top:3px;
          }
        }
      }
    }

    .seach-bx {
      width:400px;
      // margin-right:15px;
      form {
        display: flex;
        background: #29272F;
        align-items: center;
        border-radius: 8px;
      }

      input {
        background: #29272F;
        height: 40px;
        line-height: 40px;
        border-radius: 8px;
        border: none;
        padding-left: 36px;
        color: #fff;
        font-size: 14px;
        background-image: url('../../assets/pro/header/search_icon.svg');
        background-repeat: no-repeat;
        background-position: 14px center;
        background-size: 16px 16px;
        width: 100%;
      }


      .clear-by-search {
        min-width: 14px;
        height: 14px;
        background: url('../../assets/pro/cancel_search.svg') no-repeat;
        background-size: cover;
        margin-right: 10px;
        cursor: pointer;
      }
    }
  }

  .fav-datas {
    display: flex;
    flex-wrap: wrap;
    grid-gap: 20px;

    .fav-d-item {
      // width: 312px;
      width: calc((100% - 80px) / 5);
      height: 280px;
      // margin-right: 20px;
      // margin-bottom: 20px;
      // background: #171717;
      animation: opacity .2s linear;
      border-radius: 16px;
      overflow: hidden;
      position: relative;
      transition: .1s all linear;
      // border-color: #171717;
      border: 2px solid transparent;

      &:hover {
        border-color: #11CCB1;

        .img-flex-box {
          .ops {
            display: flex;
          }
        }
      }

      &:nth-child(5n) {
        // margin-right: 0px;
      }

      &.create-btn {
        border: 2px dashed #424242;
        border-radius: 16px;
        transition: 0.1s all linear;

        a {
          // display: inline-block;
          width: 100%;
          height: 100%;
          // text-align: center;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;

          .plus-icon {
            width: 40px;
            height: 40px;
            border-radius: 40px;
            background: #29272f;
            display: block;
            text-align: center;
            line-height: 40px;
            // margin: 91px auto 18px auto;
            margin-bottom: 12px;
          }

          .text {
            font-size: 14px;
            color: #fff;
            font-weight: 500;
          }
        }

        &:hover {
          border-color: #11CCB1;
        }
      }

      .img-flex-box {
        display: flex;
        align-items: center;
        position: relative;

        .ops {
          position: absolute;
          top: 10px;
          right: 10px;
          transition: .2s all linear;

          a {
            border-radius: 12px;
            background: #FFFFFF;
            width: 40px;
            height: 40px;
            transition: .2s all linear;

            &:hover {
              // opacity:.9;
              background-color: #e1e1e1;
            }
          }

          .i-del {
            background-image: url('../../assets/pro/i_del.png');
            background-size: 22px 22px;
            background-repeat: no-repeat;
            background-position: center;
            margin-right: 10px;
          }

          .i-edit {
            background-image: url('../../assets/pro/i_edit.png');
            background-size: 22px 22px;
            background-repeat: no-repeat;
            background-position: center;
          }
        }

        .lt-img {
          min-width: 204px;
          height: 210px;
          margin-right: 6px;
          border-radius: 16px;
          overflow: hidden;
          background: #242327;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .rt-img {
          width:100%;
          .next-img {
            // width: 102px;
            height: 102px;
            margin-bottom: 6px;
            border-radius: 16px;
            overflow: hidden;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }

            background:#242327;
          }

          .last-img {
            // width: 102px;
            height: 102px;
            border-radius: 16px;
            overflow: hidden;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }

            background:#242327;
          }
        }

        .author {
          position: absolute;
          bottom: 10px;
          left: 9px;
          background: rgba(255, 255, 255, 0.9);
          border-radius: 12px;
          padding: 10px 13px;
          transition: 0.1s all linear;
          width: 164px;
          cursor: pointer;

          &:hover {
            background: rgba(255, 255, 255, 1);
          }

          .ar-tit {
            font-size: 14px;
            font-weight: 500;
            color: #383737;
            line-height: 20px;
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            background: url('../../assets/pro/take_tit_icon.svg') no-repeat;
            background-position: left center;
            padding-left: 22px;
          }

          .u-box {
            display: flex;
            padding-left: 20px;

            .name {
              font-size: 14px;
              color: #969696;
              font-weight: 500;
            }

            .avatar {
              width: 20px;
              height: 20px;
              border-radius: 20px;
              margin-right: 7px;
            }
          }
        }

        .at-btn {
          color: #fff;
          font-size: 14px;
          background-color: #11CCB1;
          border-radius: 12px;
          line-height: 44px;
          background-image: url('../../assets/pro/un_follow_ico.svg');
          background-repeat: no-repeat;
          background-position: 11px center;
          // width:82px;
          padding-left: 35px;
          padding-right: 19px;
          text-align: center;
          position: absolute;
          left: 10px;
          top: 10px;
        }

        .ated-btn {
          color: #383737;
          font-size: 14px;
          background-color: #fff;
          border-radius: 12px;
          line-height: 44px;
          background-image: url('../../assets/pro/cancel_follow_ico.svg');
          background-repeat: no-repeat;
          background-position: 11px center;
          // width:82px;
          padding-left: 35px;
          padding-right: 19px;
          text-align: center;
          position: absolute;
          left: 10px;
          top: 10px;
        }

        .edit-btn {
          color: #383737;
          font-size: 14px;
          background-color: #fff;
          border-radius: 12px;
          line-height: 44px;
          width: 40px;
          height: 40px;
          text-align: center;
          position: absolute;
          right: 10px;
          top: 10px;
          background-image: url('../../assets/pro/edit_ico.svg');
          background-repeat: no-repeat;
          background-position: center center;
        }

        .hid-el {
          // display: none;
          transition: .1s all linear;
          opacity: 0;
        }

        &:hover {
          .hid-el {
            // display: inline-block;
            opacity: 1;
          }
        }
      }

      .bot-desc {
        font-size: 16px;
        display: flex;
        justify-content: space-between;
        margin-top: 9px;
        align-items: center;
        padding-right: 15px;

        .file-name {
          color: #fff;
          font-weight: 500;
          padding-left: 15px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .file-num {
          color: #969696;
          // margin-right: 13px;
          font-size: 14px;
          white-space: nowrap;
        }
      }
    }
  }
}
</style>